
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/new_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///选择播放终端页面
class MediaSelectTerminalByPicPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "MediaSelectTerminalByPicPage";
  final String currentHsn;
  final String hsns;
  ///是否是添加已有照片到终端
  final bool addTerminal;
  final String startday;
  final String endday;
  final String picid;


  const MediaSelectTerminalByPicPage({Key key, this.currentHsn, this.hsns, this.addTerminal,
    this.startday, this.endday, this.picid,}):super(key: key);

  @override
  _MediaSelectTerminalByPicPageState createState() => _MediaSelectTerminalByPicPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, {String currentHsn, String hsns, bool addTerminal, String startday,
        String endday, String picid,}) {
    return RouterUtils.routeForFutureResult(
      context, MediaSelectTerminalByPicPage(
      currentHsn: currentHsn,
      hsns: hsns,
      addTerminal: addTerminal,
      startday: startday,
      endday: endday,
      picid: picid,
    ),
      routeName: MediaSelectTerminalByPicPage.ROUTER,
    );
  }
}

class _MediaSelectTerminalByPicPageState extends BaseState<MediaSelectTerminalByPicPage>{
  NewTerminalListViewModel _viewModel;
  TerminalDetailViewModel _detailViewModel;
  String _searchStr;
  bool _selectAll = false;
  String _hsns = "";
  @override
  void initState() {
    super.initState();
    _viewModel = NewTerminalListViewModel(this, searchStrFunc: () => _searchStr, allflg: "01");
    _hsns = widget.hsns;
    _viewModel.getTerminalListByPic(context, widget?.picid, _hsns, terminalname: _searchStr);
    VgEventBus.global.on().listen((event) {
      if(event is TerminalListRefreshEvent){
        _viewModel.refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(
        child: _toPlaceHolderWidget(),
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "请选择",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  ///搜索
  Widget _toSearchWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: <Widget>[
          SizedBox(height: 10),
          CommonSearchBarWidget(
            hintText: "搜索名字",
            // onChanged: (String searchStr) => _searchStr = searchStr,
            onSubmitted: (String searchStr) {
              _searchStr = searchStr;
              _viewModel.getTerminalListByPic(context, widget?.picid, _hsns, terminalname: _searchStr);
            },
          ),
        ],
      ),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.picid, widget?.hsns),
            loadingOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.picid, widget?.hsns),
            child: child,
          );
        },
        child: _toBodyWidget());
  }


  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalByPicValueNotifier,
        builder: (BuildContext context, TerminalByPicDataBean detailBean, Widget child){

          List<NewTerminalListItemBean> selectedList = new List();
          NewTerminalListItemBean currentBean;
          detailBean?.terminalList?.forEach((element) {
            if(element?.hsn == widget?.currentHsn){
              currentBean = element;
            }else{
              selectedList.add(element);
            }
          });

          return CommonPackUpKeyboardWidget(
            child: Column(
              children: <Widget>[
                _toTopBarWidget(),
                _toSearchWidget(),
                _toHintWidget(selectedList, currentBean),
                Expanded(
                    child: _toListWidget(selectedList, detailBean?.usehsnList)),
                _toConfirmWidget(selectedList, detailBean?.usehsnList),
              ],
            ),
          );
        }
    );
  }

  Widget _toHintWidget(List<NewTerminalListItemBean> data, NewTerminalListItemBean currentBean){
    return Visibility(
      visible: currentBean != null,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          VgToastUtils.toast(context, "不可取消当前终端显示屏");
        },
        child: Column(
          children: [
            Container(
              height: 39,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 12),
              child: Text(
                "当前终端显示屏：",
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
                ),
              ),
            ),
            Container(
              height: 87,
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 15),
                    child: Image.asset(
                      "images/common_selected_ico.png",
                      height: 20,
                    ),
                  ),
                  Expanded(child: _toContentWidget(0, currentBean)),
                ],
              ),
            ),
            Visibility(
              visible: (data != null && data.length > 0),
              child: Container(
                height: 10,
                color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
              ),
            ),
            Visibility(
              visible: (data != null && data.length > 0),
              child: Container(
                height: 39,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(left: 12),
                child: Text(
                  "同步上传至其他终端：",
                  style: TextStyle(
                      fontSize: 12,
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///图片展示栏
  Widget _toListWidget(List<NewTerminalListItemBean> data, List<NewTerminalListItemBean> terminalList){
    List<String> pichsnList = new List();
    if(terminalList != null && terminalList.length > 0){
      terminalList.forEach((element) {
        pichsnList.add(element.hsn);
      });
    }
    if(data != null){
      if(StringUtils.isNotEmpty(_hsns??"")){
        List<String> hsnList = _hsns.split(",");
        int count = 0;
        if(hsnList != null && hsnList.length > 0){
          data.forEach((element) {
            if(hsnList.contains(element.hsn)){
              element.selectStatus = true;
              count++;
            }
          });
        }
        if(count == data?.length??0){
          _selectAll = true;
        }
      }
    }
    return ListView.separated(
      padding: EdgeInsets.only(top: 0),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index, data?.elementAt(index), data, pichsnList);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox();
      },
      itemCount: data?.length??0,
    );

  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, NewTerminalListItemBean itemBean,
      List<NewTerminalListItemBean> data, List<String> pichsnList){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ()  {
        // if((pichsnList.contains((itemBean?.hsn??"")))){
        //   return;
        // }
        setState(() {
          itemBean.selectStatus = !itemBean.selectStatus??false;
          _selectAll = _getSelectedCount(data, pichsnList) == data?.length;
          _hsns = _getHsns(data, pichsnList);
        });
      },
      child: Container(
        height: 87,
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                itemBean.selectStatus??false
                    ? "images/common_selected_ico.png"
                    : "images/common_unselect_ico.png",
                // (pichsnList.contains((itemBean?.hsn??"")))?"images/icon_select_disable.png":
                // (itemBean.selectStatus??false
                //     ? "images/common_selected_ico.png"
                //     : "images/common_unselect_ico.png"),
                height: 20,
              ),
            ),

            Expanded(child: _toContentWidget(index, itemBean)),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(int index, NewTerminalListItemBean itemBean) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Expanded(
                child: Text(
                  StringUtils.isNotEmpty(itemBean?.getTerminalName(index))
                      ? (itemBean?.getTerminalName(index))
                      : "终端显示屏${(index ?? 0) + 1}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Visibility(
                child: Container(
                  alignment: Alignment.centerRight,
                  width: 60,
                  child: Text(
                    (itemBean?.onOff == null || itemBean?.onOff !=1)?"已关机":"开机状态",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: (itemBean?.onOff == null || itemBean?.onOff !=1)
                          ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                          :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Container(
            width: 236,
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 4,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          )
        ],
      ),
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  int _getSelectedCount(List<NewTerminalListItemBean> data, List<String> pichsnList){
    int count = 0;
    if(data != null){
      data.forEach((element) {
        //去除已有终端判断
        // if((element.selectStatus??false) && !pichsnList?.contains(element.hsn)){
        //   count++;
        // }
        if((element.selectStatus??false)){
          count++;
        }
      });
    }
    return count;
  }

  ///确定
  Widget _toConfirmWidget(List<NewTerminalListItemBean> data, List<NewTerminalListItemBean> terminalList){
    List<String> pichsnList = new List();
    if(terminalList != null && terminalList.length > 0){
      terminalList.forEach((element) {
        pichsnList.add(element.hsn);
      });
    }
    return Visibility(
      visible: (data != null && data.length > 0),
      child: Container(
        height: 56,
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
        child: Row(
          children: <Widget>[
            GestureDetector(
              onTap: (){
                setState(() {
                  data.forEach((element) {
                    element.selectStatus = !_selectAll;
                  });
                  _selectAll = !_selectAll;
                  _hsns = _getHsns(data, pichsnList);
                });
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Text(
                  _selectAll?"全不选":"全选",
                  style: TextStyle(
                    fontSize: 15,
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  ),
                ),
              ),
            ),
            Visibility(
              visible: _getSelectedCount(data, pichsnList) > 0,
              child: Text(
                "已选${_getSelectedCount(data, pichsnList)}终端",
                style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                ),
              ),
            ),
            Spacer(),
            CommonFixedHeightConfirmButtonWidget(
              isAlive: true,
              height: 36,
              width: 90,
              margin: const EdgeInsets.symmetric(horizontal: 15),
              unSelectBgColor: Color(0xFF3A3F50),
              selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              unSelectTextStyle: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 15,
              ),
              selectedTextStyle: TextStyle(
                color: Colors.white,
                fontSize: 15,
                // fontWeight: FontWeight.w600
              ),
              text: "确定",
              onTap: (){
                if(widget?.addTerminal??false){
                  if(StringUtils.isNotEmpty((widget?.hsns??"")) && StringUtils.isEmpty(_getHsns(data, pichsnList))){
                    //取消所有选择的终端，走取消接口
                    _detailViewModel.cancelFolder(context, widget?.picid);

                  }else{
                    _viewModel.addMediaToTerminals(context, (_getSelectedCount(data, pichsnList) == data?.length)?"01":"00",
                        widget?.startday, widget?.endday, _getHsns(data, pichsnList), widget?.picid);
                  }
                }else{
                  RouterUtils.pop(context, result: _getHsns(data, pichsnList));
                }

              },
            ),
          ],
        ),
      ),
    );
  }

  String _getHsns(List<NewTerminalListItemBean> data, List<String> pichsnList){
    String hsns = "";
    data.forEach((element) {
      //去除已有终端判断
      // if(element.selectStatus && !pichsnList?.contains(element.hsn)){
      //   hsns += element.hsn;
      //   hsns += ",";
      // }
      if(element.selectStatus){
        hsns += element.hsn;
        hsns += ",";
      }
    });
    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }



}